/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.net.Uri;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ouertech.android.agm.lib.base.constant.CstScheme;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.MenuTxt;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Image;
import com.simon.mengkou.data.bean.base.Invitation;
import com.simon.mengkou.data.bean.req.UserModifyReq;
import com.simon.mengkou.data.enums.EFileBelong;
import com.simon.mengkou.data.enums.ESex;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.base.BaseSelectImageActivity;
import com.simon.mengkou.ui.dialog.SexDialog;
import com.simon.mengkou.utils.UtilOuer;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/3/27.
 * desc    : 编辑个人信息界面
 */
public class UserModifyActivity extends BaseSelectImageActivity{
    //头像
    @Bind(R.id.user_id_avatar)
    SimpleDraweeView mSdvAvatar;
    //昵称
    @Bind(R.id.user_id_nick)
    EditText mEtNick;
    //地址
    @Bind(R.id.user_id_address)
    EditText mEtAddress;
    //性别
    @Bind(R.id.user_id_sex)
    TextView mTvSex;
    //年龄
    @Bind(R.id.user_id_age)
    EditText mEtAge;


    //邀请码
    @Bind(R.id.user_id_code_root)
    LinearLayout mLlCodeRoot;
    @Bind(R.id.user_id_code)
    EditText mEtCode;

    //图片选择地址
    private String mPath;
    private SexDialog mSexDialog;

    private String mNick;
    private String mAddr;
    private int mAge;
    private int mSex;
    private String mAvatarKey;
    private String mAvatar;
    private String mCode;

    @Override
    protected void initTop() {
        setTitle(R.string.user_modify_title);
        setNavigation(R.drawable.common_ic_left_nav);

        //保存编辑信息
        MenuTxt txt = new MenuTxt.MenuTxtBuilder(this)
            .setTitle(R.string.common_save)
            .setListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    commit();
                    return false;
                }
            }).build();

        addMenu(txt);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_user_modify);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        //头像
        OuerApplication.mImageLoader.loadAvatar(mSdvAvatar, OuerApplication.mUser.getAvatarUrl());
        //昵称
        mEtNick.setText(OuerApplication.mUser.getNick());
        //地址
        mEtAddress.setText(OuerApplication.mUser.getLocation());
        if(UtilString.isBlank(OuerApplication.mUser.getLocation())) {
            location();
        }
        //性别
        if(OuerApplication.mUser.getSex() == ESex.MALE) {
            mTvSex.setText(R.string.user_modify_sex_male);
        } else {
            mTvSex.setText(R.string.user_modify_sex_female);
        }
        //年龄
        mEtAge.setText(String.valueOf(OuerApplication.mUser.getAge()));

        //邀请
        mLlCodeRoot.setVisibility(View.GONE);
        isInvitation();
    }

    /**
     * 选择图片
     */
    @OnClick(R.id.user_id_avatar)
    public void selectPicture() {
        selectPicture(mSdvAvatar);
    }


    @Override
    public void onPhotoCropped(Uri uri) {
        super.onPhotoCropped(uri);
        if(uri != null) {
            String url = uri.toString();
            mPath = url.replace(CstScheme.FILE, "");
            OuerApplication.mImageLoader.loadAvatar(mSdvAvatar, url);
        }
    }

    /**
     * 性别选择
     */
    @OnClick(R.id.user_id_sex)
    public void choiceSex() {
        if(mSexDialog == null) {
            mSexDialog = new SexDialog(this, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(view.getId() == R.id.sex_id_male) {
                        mTvSex.setText(R.string.user_modify_sex_male);
                    } else {
                        mTvSex.setText(R.string.user_modify_sex_female);
                    }

                    mSexDialog.dismiss();
                }
            });
        }

        mSexDialog.showAtLocation(mTvSex, Gravity.CENTER, 0, 0);
    }

    /**
     * 收货地址管理
     */
    @OnClick(R.id.user_id_order_addr)
    public void addOrderAddr() {
        OuerDispatcher.presentAddressManagerActivity(this);
    }

    /**
     * 提交修改信息
     */
    private void commit() {
        //昵称
        mNick = mEtNick.getText().toString().trim();
        //地址
        mAddr = mEtAddress.getText().toString().trim();
        //性别
        mSex = ESex.FEMALE;
        if(mTvSex.getText().equals(getString(R.string.user_modify_sex_male))) {
            mSex = ESex.MALE;
        } else {
            mSex = ESex.FEMALE;
        }

        //年龄
        mAge = Integer.valueOf(mEtAge.getText().toString().trim());
        if(mAge <=0 || mAge > 100) {
            mEtAge.requestFocus();
            UtilOuer.toast(this, R.string.user_modify_age_error);
            return;
        }

        //邀请码
        mCode = mEtCode.getText().toString().trim();

        if(UtilString.isNotBlank(mPath)) {
            uploadAvatar();
        } else {
            userModify();
        }
    }


    /**
     * 上传头像
     */
    private void uploadAvatar() {
        List<String> files = new ArrayList<>();
        files.add(mPath);

        AgnettyFuture future = OuerApplication.mOuerFuture.uploadImages(
                files, EFileBelong.PRODUCT,
                new OuerFutureListener(this) {
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        setWaitingDialog(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        List<Image> images = (List<Image>) result.getAttach();
                        if(UtilList.isNotEmpty(images)){
                            Image image = images.get(0);
                            mAvatarKey = image.getKey();
                            mAvatar = image.getUrl();
                        }

                        userModify();
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);
                        UtilOuer.showExceptionToast(UserModifyActivity.this, result,
                                R.string.user_modify_save_failure);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }
                }
        );

        attachDestroyFutures(future);
    }

    /**
     * 提交修改用户信息
     */
    private void userModify() {
        UserModifyReq req = new UserModifyReq();
        req.setUid(OuerApplication.mUser.getUserId());
        req.setNick(mNick);
        req.setAge(mAge);
        if(UtilString.isNotBlank(mAvatarKey)) {
            req.setAvatarKey(mAvatarKey);
        }
        req.setLocation(mAddr);
        req.setSex(mSex);
        req.setAvatar(mAvatar);

        if(UtilString.isNotBlank(mCode)) {
            req.setMachineCode(OuerApplication.mAppInfo.getDeviceId());
            req.setInvitationCode(mCode);
        }

        AgnettyFuture future = OuerApplication.mOuerFuture.userModify(req,
                new OuerFutureListener(this) {
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        if(UtilString.isBlank(mPath)) {
                            setWaitingDialog(true);
                        }
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setWaitingDialog(false);
                        Boolean flag = (Boolean) result.getAttach();
                        if(flag) {
                            UtilOuer.toast(mContext, R.string.user_modify_save_success);
                            finish();
                        } else {
                            UtilOuer.showExceptionToast(UserModifyActivity.this, result,
                                    R.string.user_modify_save_failure);
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);

                        //异常提示
                        UtilOuer.showExceptionToast(UserModifyActivity.this, result,
                                R.string.user_modify_save_failure);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }
                }
        );

        attachDestroyFutures(future);
    }

    /**
     * 百度定位
     */
    private void location() {
        final LocationClient locationClient = new LocationClient(this);
        BDLocationListener locationListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                Address address = bdLocation.getAddress();
                String location = address.city + "-" + address.street;
                OuerApplication.mUser.setLocation(location);
                mEtAddress.setText(location);
                locationClient.stop();
            }
        };

        locationClient.registerLocationListener(locationListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        option.setIsNeedAddress(true);
        locationClient.setLocOption(option);
        locationClient.start();
    }


    private void isInvitation() {
        AgnettyFuture future = OuerApplication.mOuerFuture.isInvition(
                OuerApplication.mUser.getUserId(),
                OuerApplication.mAppInfo.getDeviceId(),
                new OuerFutureListener(this) {
                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        Invitation flag = (Invitation) result.getAttach();
                        if(UtilString.isBlank(flag.getResult())) {//未被邀请
                            mLlCodeRoot.setVisibility(View.VISIBLE);
                        } else {//已邀请
                            mLlCodeRoot.setVisibility(View.GONE);
                        }

                    }
                }
            );

        attachDestroyFutures(future);
    }

}
